<template>
  <div class="UploadThesis">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学号" prop="sNo">
            <el-input v-model="form.sNo" placeholder="请输入学号" @blur="getSName" :disabled="edit"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="sName">
            <el-input v-model="form.sName" readonly="readonly" placeholder="填入学号自动获取姓名"></el-input>
        </el-form-item>
        <el-form-item label="题目" prop="thesisTitle">
            <el-input v-model="form.thesisTitle" placeholder="请输入题目" @blur="getKeyword"></el-input>
        </el-form-item>
        <el-form-item label="关键词">
            <div class="item">
              <div class="keyWord clearfix">
                <div class="keywords_label" v-for="(item, index) in keywordArr" :key="index">
                  <span name="keywordspan" class="keywordspan" onclick="keyWordEdit(this)">{{item}}</span>
                  <i class="delIcons" @click="delKeyword(item)"></i>
                </div>
              </div>
              <div class="keyWordInput">
                <input type="text" class = "keyInput" v-model="keyword" @keydown.enter="addKeyword" placeholder="请在此输入关键词，组之间用【回车符】隔开">
              </div>
            </div>
        </el-form-item>
        <el-form-item label="论文" prop="thesisFileName">
          <div class="item uploadItem">
            <el-upload
                class="upload-demo"
                action="/api/thesisInfo/uploadThesis"
                :data="myData"
                ref="thesisFile"
                accept=".doc,.docx,.pdf"
                :show-file-list="false"
                :on-change="addThesisFile"
                :on-success="uploadTheFileSucc"
                :on-error="uploadTheFileError"
                :auto-upload="false"
                >
                <input type="text" class="uploadInput" v-model="form.thesisFileName" readonly>
                <i class="el-icon-upload uploadIcon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="附件">
          <div class="item uploadItem">
            <el-upload
              class="upload-demo"
              :data="myData"
              action="/api/thesisInfo/uploadEnclosure"
              ref="enclosureFile"
              :show-file-list="false"
              :on-change="addEnclosureFile"
              :on-success="uploadEncFileSucc"
              :on-error="uploadEncFileError"
              :auto-upload="false"
              >
              <input type="text" class="uploadInput" v-model="form.enclosureFileName" readonly>
              <i class="el-icon-upload uploadIcon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>
import { _querySname, _getKeywords, _updateTiltleKeyword } from '../../network/dissertation.js'

export default {
  name: 'UploadThesis',
  props: ['graSort', 'thesisData'],
  data () {
    var checkSno = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请填写学号'))
        } else if (!this.isCellSno(value)) { // 引入methods中封装的检查手机格式的方法
            callback(new Error('请填写正确的学号!'))
        } else {
            callback()
        }
    }
    return {
        form: {
          sNo: '1708030204',
          sName: '',
          thesisTitle: '基于springboot的毕业生数据可视化系统',
          keywords: '',
          thesisFileName: '',
          enclosureFileName: '',
          gradeId: 0,
          majorId: 0,
          teamId: 0
        },
        thesisFileList: [],
        enclosureFileList: [],
        rules: {
            sNo: [
                { required: true, validator: checkSno, trigger: 'blur' }
            ],
            sName: [
                { required: true, message: '姓名为必填项', trigger: 'blur' }
            ],
            thesisTitle: [
                { required: true, message: '题目为必填项', trigger: 'blur' }
            ],
            thesisFileName: [
                { required: true, message: '请上传论文', trigger: 'blur' }
            ],
        },
        successNum: 0,
        keyword: '',
        keywordArr: [],
        edit: false
    }
  },
  computed: {
    // 上传文件时携带的额外数据，即表单数据
    myData() {
        return this.form
    }
  },
  mounted () {
    if(typeof(this.thesisData.keywords) !== 'undefined'){
      this.form = this.thesisData
      this.keywordArr = this.form.keywords.split(',')
      this.edit = true
    }
  },
  methods: {
      onSubmit() {
        this.$refs['form'].validate((valid) => {
            if (valid) {
              this.form.sNo = parseInt(this.form.sNo)
              this.form.teamId = this.graSort.team
              if( this.thesisFileList.length > 0 && this.enclosureFileList.length > 0){       //上传了论文和附件
                this.form.enclosureFileName = ''
                this.$refs.thesisFile.submit();
                setTimeout(()=>{
                  this.$refs.enclosureFile.submit();
                },500)
              } else if(this.thesisFileList.length > 0){     //上传了论文
                this.form.enclosureFileName = ''
                this.$refs.thesisFile.submit();
              } else if(this.enclosureFileList.length > 0){     //上传了附件
                  this.$refs.enclosureFile.submit();
              } else{                                   //只修改了数据
                _updateTiltleKeyword(this.form.sNo, this.form.thesisTitle, this.form.keywords).then(res => {
                  if(res.data.code === 200){
                    this.$message.success('提交成功')
                    setTimeout(() => {
                      this.$parent.$parent.closeUploadThesis()
                      /* 刷新父组件表格 */
                      this.$parent.$parent.onSearch()
                    },500)
                  } else {
                    this.$message.error(res.data.msg)
                  }
                }).catch(res => {
                  this.$message.error("接口未知错误")
                })
              }
              
            } else {
                this.$message.error('请填写完整')
                return false
            }
        })
      },
      /* 上传论文文件成功 */
      uploadTheFileSucc (response, file, fileList) {
        this.$message.success('上传论文成功')
        setTimeout(() => {
          this.$parent.$parent.closeUploadThesis()
          /* 刷新父组件表格 */
          this.$parent.$parent.onSearch()
        },500)
      },
      /* 上传论文文件失败 */
      uploadTheFileError (err, file, fileList) {
        this.$message.error(err)
      },
      /* 上传附件文件成功 */
      uploadEncFileSucc (response, file, fileList) {
        this.$message.success('上传附件成功')
        setTimeout(() => {
          this.$parent.$parent.closeUploadThesis()
          /* 刷新父组件表格 */
          this.$parent.$parent.onSearch()
        },500)
      },
      /* 上传附件文件失败 */
      uploadEncFileError (err, file, fileList) {
        this.$message.error(err)
      },
      /* 添加论文文件 */
      addThesisFile (file, fileList) {
        // file为选择的文件   fileList为已选择的文件列表
        var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
        if(testmsg === 'doc' || testmsg === 'docx' || testmsg === 'pdf') {
          this.thesisFileList = fileList
          this.form.thesisFileName = file.name
        }
        else{
          this.$message.error('上传文件只能是doc、docx、pdf格式!')
        }
      },
      /* 添加附件文件 */
      addEnclosureFile (file, fileList) {
        this.enclosureFileList = fileList
        this.form.enclosureFileName = file.name
      },
      /* 添加关键词 */
      addKeyword () {
        if(this.keyword !== ''){
          this.keywordArr.push(this.keyword)
          this.form.keywords = this.keywordArr.join(',')
          this.keyword = ''
        } else {
          this.$message.info('请输入关键词')
        }
      },
      /* 清空数据 */
      emptyData () {
          this.$refs['form'].resetFields()
          this.$refs.thesisFile.clearFiles()
          this.$refs.enclosureFile.clearFiles()
      },
      /* 取消 */
      cancel () {
          this.emptyData()
          this.$parent.$parent.closeUploadThesis()
      },
      /* 检查学号 */
      isCellSno (val) {
        if (!/^\d{10}$/.test(val)) {
          return false
        } else {
          return true
        }
      },
      /* 根据学号获取姓名 */
      getSName () {
        if(this.form.sNo !== ''){
            if(typeof(this.thesisData.keywords) === 'undefined'){
              
            }
            _querySname(this.form.sNo).then(res => {
                if(res.data.code == 200){
                    this.form.sName = res.data.msg
                }
                else{
                    this.$message.error(res.data.msg)
                    this.form.sName = ''
                }
            }).catch(res => {
                this.$message.error("获取姓名失败，请联系管理员")
            })
        }
      },
      /* 删除关键字 */
      delKeyword (keyword){
        let index = this.keywordArr.findIndex(item => {
          return item == keyword
        })
        this.keywordArr.splice(index, 1)
        this.form.keywords = this.keywordArr.join(',')
      },
      /* 编辑关键字 */
      editKeyword (keyword){
        this.keyword = keyword
      },
      /*根据题目获取关键字 */
      getKeyword () {
        _getKeywords(this.form.thesisTitle).then(res => {
          if(res.data.code == 200){
            this.keywordArr = res.data.keywordList
            this.form.keywords = this.keywordArr.join(',')
          }
          else{
            this.$message.error("获取关键词错误")  
          }
        }).catch(res => {
          this.$message.error("接口错误，请联系管理员")
        })
      }
  }
}
</script>

<style>
.el-tag{
  margin-right: 5px;
  margin-top: 5px;
}
</style>
<style scoped>
.item{
  border: 1px solid #DCDFE6;
  border-radius: 4px;
}
.item .keyWord{
  height: 84px;
  overflow: auto;
  padding: 10px 10px 0;
}
.keyWord .keywords_label {
    float: left;
    padding: 4px 25px 4px 4px;
    background: #e1f6fb;
    color: #333;
    border-radius: 3px;
    margin: 0 10px 6px 0;
    position: relative;
    cursor: pointer;
    line-height: 18px;
}
.keyWord .keywords_label .delIcons {
    width: 15px;
    height: 15px;
    background: url(../../assets/img/btn_delete.png) no-repeat;
    position: absolute;
    right: 4px;
    top: 5px;
    cursor: pointer;
}
.keyWord .keywords_label .delIcons:hover{ opacity: 0.8; }

.item .keyWordInput{
  height: 42px;
  color: #b2b2b2;
  line-height: 16px;
  padding: 0 10px 10px;
  position: relative;
}
.item .keyWordInput .keyInput{
  height: 100%;
  width: 100%;
  border: 0;
  outline: 0;
}
.keyWord .keywords_label{ float: left; padding:4px 25px 4px 4px; background: #e1f6fb; color: #333; border-radius: 3px; margin:0 10px 6px 0; position: relative; cursor: pointer; line-height:18px}
.keyWord .keywords_label:hover,
.keyWord .keywords_label.on{ background: #cdf3fe; }

.uploadItem{
  position: relative;
  width: 50%;
  overflow: hidden;
}
.uploadItem .uploadIcon{
  position: absolute;
  right: 8px;
  top: 10px;
  font-size: 20px;
}
.uploadItem .uploadInput{
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  padding: 0 30px 0 10px;
  border: 0;
  outline: 0;
}
</style>

